
.sp2pnt <- function(obj) {
  pnts <- obj@coords
  pnt.count <- nrow(pnts)
  result.geos = vector(mode="list", pnt.count)
  for(i in c(1:pnt.count)){
    geo = CreatePoint(pnts[i, 1],pnts[i, 2])
    result.geos[i] <- list(geo)
  }
  return(result.geos)
}

.sp2line <- function(obj) {
  lines.count <- length(obj@lines)
  result.lines <- vector(mode="list", lines.count)
  
  for(i in c(1:lines.count)){
    lines <- obj@lines[[i]]
    id <- lines@ID
    sublines <- lines@Lines
    sublines.count <- length(sublines)
    
    polys <- c(length=sublines.count)
    for(j in c(1:sublines.count)){
      subline <- sublines[[j]]
      subline.pnts <- subline@coords
      polys[j] <- nrow(subline.pnts)
    }
    
    pnts.count <- sum(polys)
    xs <- c()
    ys <- c()
    
    pnts <- matrix(nrow=pnts.count, ncol=2)
    for(j in c(1:sublines.count)){
      subline <- sublines[[j]]
      subline.pnts <- subline@coords
      xs <- c(xs, subline.pnts[, 1])
      ys <- c(ys, subline.pnts[, 2])
    }
    pnts[, 1] <- xs
    pnts[, 2] <- ys
    geoLine = CreateLine(pnts, polys)
    if (!is.null(geoLine)) {
      if(is.numeric(id)) {
        SetID(geoLine, as.integer(id))
      }
      result.lines[i] <- list(geoLine)
    }
  }
  return(result.lines)
}

.sp2region <- function(obj) {
  regions.count = length(obj@polygons)
  result.regions <- vector("list", regions.count)
  for(i in c(1:regions.count)){
    polygons <- obj@polygons[[i]]
    id <- polygons@ID
    subPolygons <- polygons@Polygons
    subPolygons.count <- length(subPolygons)
    
    polys <- c(length=subPolygons.count)
    for(j in c(1:subPolygons.count)){
      subPolygon <- subPolygons[[j]]
      subPolygon.pnts <- subPolygon@coords
      polys[j] <- nrow(subPolygon.pnts)
    }
    
    pnts.count <- sum(polys)
    xs <- c()
    ys <- c()
    
    pnts <- matrix(nrow=pnts.count, ncol=2)
    for(j in c(1:subPolygons.count)){
      subPolygon <- subPolygons[[j]]
      subPolygon.pnts <- subPolygon@coords
      xs <- c(xs, subPolygon.pnts[, 1])
      ys <- c(ys, subPolygon.pnts[, 2])
    }
    pnts[, 1] <- xs
    pnts[, 2] <- ys
    geoRegion = CreateRegion(pnts, polys)
    if (!is.null(geoRegion)) {
      if(is.numeric(id)){
        SetID(geoRegion, as.integer(id))
      }
      result.regions[i] <- list(geoRegion)
    }
  }
  return(result.regions)
}


Sp2Geometry <- function(obj){
  
  if (is.null(obj)) {
    stop("obj is null.")
  }
  sp.classname <- class(obj)
  
  if (sp.classname == "SpatialPoints") {
    return(.sp2pnt(obj))
  } else if (sp.classname == "SpatialLines") {
    return(.sp2line(obj))
  } else if (sp.classname == "SpatialPolygons") {
    return(.sp2region(obj))
  } else {
    stop("Unsupported sp object. Only support SpatialPoints, SpatialLines and SpatialPolygons.")
  }
}